<?php
// +----------------------------------------------------------------------
// | Author: wyd 2025/10/26
// | DESC: 优化方法
// +----------------------------------------------------------------------

declare (strict_types=1);


namespace Study\laravel\db;

use Illuminate\Database\Capsule\Manager;

/**
 * @mixin Manager
 */
class DbManager
{
    private $config = [];

    private $manager;
    private $defaultConnection;

    private $currentConnection;
    private $isTemp = false;

    public function __construct()
    {

        $configs = $this->getConfig();
        $this->manager = new Manager();

        // 为单一 Manager 添加所有连接
        foreach ($configs as $name => $config) {
            $this->manager->addConnection($config, $name);
        }

        if (isset($configs['default'])) {
            $default = 'default';
        } else {
            $default = array_key_first($configs);
        }
        $this->defaultConnection = $default;

        //设置全局访问
        $this->manager->setAsGlobal();
        //启动Eloquent
        $this->manager->bootEloquent();
    }

    public function getConfig()
    {
        return $this->config = $this->config ?: require_once(__DIR__ . '/config.php');
    }


    public function connection(string $name = '')
    {
        if (!array_key_exists($name, $this->config)) {
            throw new \InvalidArgumentException("{$name}的数据库连接不存在");
        }
        // 切换当前连接
        $this->currentConnection = $name;
        //标记是临时链接
        $this->isTemp = true;
        return $this;
    }


    //获取一定是当前的数据库
    public function __call($methodName, $args)
    {
        //这里就是调用官方本身的方法$capsule::connection()
        $res = $this->manager::connection($this->currentConnection)->$methodName(...$args);
        if($this->isTemp){
            //切换当前数据库
            $this->currentConnection = $this->defaultConnection;
        }

        return $res;
    }

}